package com.zxlspace.Chapter1.handle;

import com.zxlspace.Chapter1.exception.MyException;
import com.zxlspace.Chapter1.pojo.ErrorInfo;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zhangxiaolin@zhonhajt.com
 * @Title: controller异常统一处理
 * @Package com.zxlspace.Chapter1.exception
 * @Description:
 * @date 2018/6/7 16:35
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final String DEFAULT_ERROR_VIEW = "error";

    //@ExceptionHandler，异常处理器，此注解的作用是当出现其定义的异常时进行处理的方法
    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultHandler(HttpServletRequest request, Exception e) {
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", request.getRequestURL());
        mav.addObject(DEFAULT_ERROR_VIEW);
        return mav;
    }

    @ExceptionHandler(value = MyException.class)
    public ErrorInfo<String> jsonErrorHandler(HttpServletRequest request, MyException e) {
        ErrorInfo<String> errorInfo = new ErrorInfo<>();
        errorInfo.setCode(ErrorInfo.ERROR);
        errorInfo.setMessage(e.getMessage());
        errorInfo.setData("Some Data");
        errorInfo.setUrl(request.getRequestURL().toString());
        return errorInfo;
    }
}
